<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="uid">
        <el-select v-model="queryParams.uid" placeholder="请选择用户" style="width: 200px;" @keyup.enter="handleQuery">
          <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="核销号码" prop="verificationCode">
        <el-input v-model="queryParams.verificationCode" placeholder="请输入核销号码" clearable @keyup.enter="handleQuery" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="服务类别" prop="serviceTypeId">
        <el-select v-model="queryParams.serviceTypeId" placeholder="请选择服务类型" style="width: 200px;"
          @keyup.enter="handleQuery">
          <el-option v-for="service_type in service_typeList" :key="service_type.id" :label="service_type.name"
            :value="service_type.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务编号" prop="serviceId">
        <el-input v-model="queryParams.serviceId" placeholder="请输入服务编号" clearable @keyup.enter="handleQuery" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable v-model="queryParams.orderTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择下单时间" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约时间" prop="reservationTime">
        <el-date-picker clearable v-model="queryParams.reservationTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择预约时间" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="车牌编号" prop="carId">
        <el-input v-model="queryParams.carId" placeholder="请输入车牌编号" clearable @keyup.enter="handleQuery" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="实付价格" prop="price">
        <el-input v-model="queryParams.price" placeholder="请输入实付价格" clearable @keyup.enter="handleQuery" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="支付状态" prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="请选择支付状态" clearable style="width: 200px;">
          <el-option label="已支付" value="0" />
          <el-option label="未支付" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label=" 支付时间" prop="payTime">
        <el-date-picker clearable v-model="queryParams.payTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择支付时间" style="width: 200px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable style="width: 200px;">
          <el-option v-for="orderStatus in orderStatuses" :key="orderStatus.value" :label="orderStatus.label"
            :value="orderStatus.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否评价" prop="evaluate">
        <el-select v-model="queryParams.evaluate" placeholder="请选择是否评价" clearable style="width: 200px;">
          <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['chy:orders:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['chy:orders:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['chy:orders:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['chy:orders:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单序号" align="center" prop="id" fixed="left" />
      <el-table-column label="用户姓名" align="center" prop="uid">
        <template #default="scope">
          <span>{{ getUserNameById(scope.row.uid) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="核销号码" align="center" prop="verificationCode" />
      <el-table-column label="核销图片" align="center" prop="verificationImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.verificationImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="服务编号" align="center" prop="serviceId" />
      <el-table-column label="服务类别" align="center" prop="serviceTypeId">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.serviceTypeId)">
            {{ getServiceNameById(scope.row.serviceTypeId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reservationTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reservationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌编号" align="center" prop="carId" width="110">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.carId}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="实付价格" align="center" prop="price" />
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template #default="scope">
          <el-tag :type="getPayStatusTagType(scope.row.payStatus)">
            {{ getPayStatusName(scope.row.payStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label=" 支付时间" align="center" prop="payTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" width="120">
        <template #default="scope">
          <el-tag :type="getOrderStatusTagType(scope.row.status)">{{ getOrderStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否评价" align="center" prop="evaluate">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.evaluate" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['chy:orders:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['chy:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户姓名" prop="uid">
          <el-select v-model="form.uid" placeholder="请选择用户" @change="fillCarNums">
            <el-option v-for="user in usersList" :key="user.id" :label="user.userName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="核销号码" prop="verificationCode">
          <el-input v-model="form.verificationCode" placeholder="请输入核销号码" />
        </el-form-item>
        <el-form-item label="核销图片" prop="verificationImg">
          <image-upload v-model="form.verificationImg" />
        </el-form-item>
        <el-form-item label="服务类别" prop="serviceTypeId">
          <el-select v-model="form.serviceTypeId" placeholder="请选择服务类型" @change="fillServiceId">
            <el-option v-for="service_type in service_typeList" :key="service_type.id" :label="service_type.name"
              :value="service_type.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务编号" prop="serviceId">
          <el-input v-model="form.serviceId" placeholder="请输入服务编号" :disabled="true" />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker clearable v-model="form.orderTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择下单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="reservationTime">
          <el-date-picker clearable v-model="form.reservationTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车牌编号" prop="carId">
          <el-select
            v-model="form.carId"
            placeholder="请选择车牌号"
            :disabled="!form.uid"
          >
            <el-option v-for="carNum in availableCarNums" :key="carNum" :label="carNum" :value="carNum" />
          </el-select>
          <el-tag v-if="form.carId" closable @close="clearCarNum" style="margin-top: 5px;">
            {{ form.carId }}
          </el-tag>
        </el-form-item>
        <el-form-item label="优惠卷号" prop="couponId">
          <el-input v-model="form.couponId" placeholder="请输入优惠卷号" />
        </el-form-item>
        <el-form-item label="实付价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入实付价格" />
        </el-form-item>
        <el-form-item label="支付状态" prop="payStatus">
          <el-select v-model="form.payStatus" placeholder="请选择支付状态">
            <el-option label="已支付" value="0" />
            <el-option label="未支付" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label=" 支付时间" prop="payTime">
          <el-date-picker clearable v-model="form.payTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择 支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态">
            <el-option v-for="orderStatus in orderStatuses" :key="orderStatus.value" :label="orderStatus.label"
              :value="orderStatus.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否评价" prop="evaluate">
          <el-select v-model="form.evaluate" placeholder="请选择是否评价">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/chy/orders"
import { listUsers } from "@/api/gas/users"
import { listService_type } from "@/api/chy/service_type"
import { listUsercarinfo } from "@/api/chy/usercarinfo"

const { proxy } = getCurrentInstance()
const { sys_yes_no } = proxy.useDict('sys_yes_no')

const ordersList = ref([])
const usercarinfoList = ref([])
const usersList = ref([])
const service_typeList = ref([])

const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    verificationCode: null,
    serviceId: null,
    serviceTypeId: null,
    orderTime: null,
    reservationTime: null,
    carId: null,
    price: null,
    payStatus: null,
    payTime: null,
    status: null,
    deleted: null,
    evaluate: null,
    uid: null
  },
  rules: {
  }
})

const availableCarNums = ref([]) // 存储当前车主可用的车牌编号
let isUpdating = false // 新增标志位，用于标记是否在修改操作中
// 选择用户后填充车牌编号
function fillCarNums(uid) {
  if (!isUpdating) {
    // 非修改操作时，更换用户姓名清空车牌编号
    form.value.carId = null
  }
  if (uid) {
    // 筛选出当前车主的车牌编号
    availableCarNums.value = usercarinfoList.value
      .filter(item => item.uid === uid)
      .map(item => item.carNum)
  } else {
    availableCarNums.value = []
    form.value.carId = null
  }
  // 操作完成后重置标志位
  isUpdating = false 
}
// 清空车牌编号选择
function clearCarNum() {
  form.value.carId = null
}

const { queryParams, form, rules } = toRefs(data)
/**
 * 根据支付状态获取对应的标签类型
 * @param {number|string} payStatus - 支付状态
 * @returns {string} 标签类型
 */
function getPayStatusTagType(payStatus) {
  payStatus = parseInt(payStatus, 10);
  switch (payStatus) {
    case 0:
      return 'success';
    case 1:
      return 'danger';
    default:
      return 'info';
  }
}

/**
 * 根据支付状态获取对应的状态名称
 * @param {number|string} payStatus - 支付状态
 * @returns {string} 状态名称
 */
function getPayStatusName(payStatus) {
  payStatus = parseInt(payStatus, 10);
  switch (payStatus) {
    case 0:
      return '已支付';
    case 1:
      return '未支付';
    default:
      return '未知状态';
  }
}
/**
 * 根据服务类型 ID 获取对应的标签类型
 * @param {number} serviceTypeId - 服务类型 ID
 * @returns {string} 标签类型
 */
function getTagType(serviceTypeId) {
  // 这里可以根据实际的服务类型 ID 来映射不同的标签类型
  // 示例：假设服务类型 ID 为 1 是 'success'，2 是 'warning'，其他是 'info'
  switch (serviceTypeId) {
    case 1:
      return 'success';
    case 2:
      return 'warning';
    case 3:
      return 'danger';
    case 4:
      return 'success';
    case 5:
      return 'primary';
    default:
      return 'info';
  }
}
const orderStatuses = ref([
  { value: 1, label: '待支付', type: 'warning' },
  { value: 2, label: '未核销', type: 'info' },
  { value: 3, label: '服务中', type: 'primary' },
  { value: 4, label: '已完成', type: 'success' },
  { value: 5, label: '已取消', type: 'danger' }
])

/**
 * 根据订单状态值获取状态标签
 * @param {number} status - 订单状态值
 * @returns {string} 订单状态标签
 */
function getOrderStatusLabel(status) {
  const statusObj = orderStatuses.value.find(s => s.value === status)
  return statusObj ? statusObj.label : '未知状态'
}

/**
 * 根据订单状态值获取对应的标签类型
 * @param {number} status - 订单状态值
 * @returns {string} 标签类型
 */
function getOrderStatusTagType(status) {
  const statusObj = orderStatuses.value.find(s => s.value === status)
  return statusObj ? statusObj.type : 'default'
}
/** 查询订单信息列表 */
function getList() {
  loading.value = true
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getListUsers() {
  loading.value = true
  queryParams.value.params = {}
  listUsers(queryParams.value).then(response => {
    usersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
/** 查询用户车辆列表 */
function getListUsersCars() {
  loading.value = true
  listUsercarinfo(queryParams.value).then(response => {
    usercarinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getUserNameById(uid) {
  const user = usersList.value.find(user => user.id == uid)
  return user ? user.userName : '未知用户'
}
function getListServiceType() {
  loading.value = true
  listService_type(queryParams.value).then(response => {
    service_typeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
function getServiceNameById(serviceTypeId) {
  const serviceType = service_typeList.value.find(serviceType => serviceType.id == serviceTypeId)
  return serviceType ? serviceType.name : '未知服务'
}

// 根据选择的服务类型 ID 填充服务编号
function fillServiceId(serviceId) {
  const serviceType = service_typeList.value.find(item => item.id === serviceId);
  if (serviceType) {
    form.value.serviceId = serviceType.id; // 假设服务类型对象中有 serviceId 属性
  } else {
    form.value.serviceId = null;
  }
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    verificationCode: null,
    verificationImg: null,
    serviceId: null,
    serviceTypeId: null,
    orderTime: null,
    reservationTime: null,
    carId: null,
    couponId: null,
    price: null,
    payStatus: null,
    payTime: null,
    status: null,
    deleted: null,
    evaluate: null,
    uid: null
  }
  proxy.resetForm("ordersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = { ...response.data }
    // 确保支付状态为字符串类型，与下拉框 value 类型一致
    form.value.payStatus = String(response.data.payStatus)
    // 设置标志位，表示正在进行修改操作
    isUpdating = true 
    // 修改时调用填充车牌编号函数
    fillCarNums(form.value.uid)
    open.value = true
    title.value = "修改订单信息"
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      // 提交前将支付状态转为数字
      if (form.value.payStatus !== null && form.value.payStatus !== undefined) {
        form.value.payStatus = parseInt(form.value.payStatus, 10)
      }
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单信息编号为"' + _ids + '"的数据项？').then(function () {
    return delOrders(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

getList()
getListUsers()
getListServiceType()
getListUsersCars()
</script>
